package 力扣.二分;

public class 山脉数组的峰顶索引852 {
    public int peakIndexInMountainArray(int[] arr) {
        if (arr == null || arr.length == 0){
            return 0;
        }
        int N = arr.length;
        return binarySearch(arr,1,N - 1);//x = [1,N - 1)
    }

    private int binarySearch(int[] arr, int i, int n) {
        int l = i ,r = n;
        while (l < r){
            int m = l + ((r - l) >> 1);
            int flag = getC(arr,m);
            if (flag == 0){
                return m;//返回的是m,不是l
            }else if (flag == 1) {//山峰在右边
                l = m + 1;
            }else {//山峰在左边
                r = m;
            }
        }
        return l;
    }

    private int getC(int[] arr, int m) {
        if (arr[m - 1] < arr[m] && arr[m] > arr[m+1]){
            return 0;
        }else if (arr[m - 1] < arr[m] && arr[m] < arr[m+1]){//山峰在右边
            return 1;
        }else {//山峰在左边
            return -1;
        }
    }
}
